package org.freeone.learning.springbootsecurity.controller;

import org.freeone.learning.springbootsecurity.security.JwtAuthenticatioToken;
import org.freeone.learning.springbootsecurity.security.SecurityUtils;
import org.freeone.learning.springbootsecurity.util.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@RestController
public class IndexController {

    @Autowired
    private AuthenticationManager authenticationManager;


    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    /**
     * 登陆跳转
     * @param modelAndView
     * @return
     */
    @GetMapping({"/login.htm"})
    public ModelAndView loginPage(ModelAndView modelAndView) {
        modelAndView.setViewName("/login.html");
        return modelAndView;
    }
    /**
     * 登陆成功
     *
     * @return
     */
    @RequestMapping({"/index"})
    public ApiResult index() {
        return ApiResult.success("登陆成功");
    }

    /**
     * 登陆失败
     *
     * @return
     */
    @RequestMapping("/loginFail")
    public ApiResult loginFail() {
        return ApiResult.fail("登陆失败");
    }

    @RequestMapping("/login.json")
    public ApiResult<JwtAuthenticatioToken> loginAjax(String username, String password, HttpServletRequest request) {
        JwtAuthenticatioToken token = SecurityUtils.login(request, username, password, authenticationManager);
        return ApiResult.successWithData(token);
    }

    @RequestMapping("/userinfo")
    public ApiResult<Authentication> getUserInformation(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return ApiResult.successWithData(authentication);
    }

}
